<!-- 选择题库 -->
<template>
    <div>
        <!-- 第一部分 -->
        <el-row class="Header">
            <el-col :span="12">
                <div>
                    <el-input placeholder="请输入题目编号 C-xxx" v-model="param.questionNumber" clearable>
                        <el-select v-model="param.chapterId" slot="prepend" placeholder="请选择">
                            <el-option v-for="(item,index) in chapters" :key="index"
                                :label="item.chapterNumber+item.description" :value="item.id"></el-option>
                        </el-select>
                        <el-button @click="getChooseQuestionlist()" slot="append" icon="el-icon-search"></el-button>
                    </el-input>
                </div>
            </el-col>

            <el-col :span="12">
                <div class="addChooseButton">
                    <el-button type="primary" @click="addChooseQuestionFold=true">添加选择题</el-button>
                </div>
            </el-col>
        </el-row>

        <!-- 添加题目对话框 -->
        <el-dialog title="添加题目" :visible.sync="addChooseQuestionFold" width="50%" :before-close="handleClose">
            <!-- form 表单 -->
            <el-form :model="addQuestionparam" :rules="rules" ref="ruleForm" label-width="100px" class="demo-ruleForm">
                <!-- 题目编号 -->
                <el-form-item label="题目编号" prop="questionNumber">
                    <el-input v-model="addQuestionparam.questionNumber">
                    </el-input>
                </el-form-item>
                <!-- 章节选择 -->
                <el-form-item label="章节选择" prop="chapterId">
                    <el-select v-model="addQuestionparam.chapterId" placeholder="请选择章节">
                        <el-option v-for="(item,index) in chapters" :key="index"
                            :label="item.chapterNumber+item.description" :value="item.id"></el-option>
                    </el-select>
                </el-form-item>
                <!-- 题目描述 -->
                <el-form-item label="题目描述" prop="description">
                    <el-input autosize type="textarea" maxlength="255"
                        v-model="addQuestionparam.description"></el-input>
                </el-form-item>
                <!-- ABCD四个选项 -->
                <el-form-item label="选项A" prop="optionA">
                    <el-input autosize type="textarea" maxlength="255" v-model="addQuestionparam.optionA"></el-input>
                </el-form-item>
                <el-form-item label="选项B" prop="optionB">
                    <el-input autosize type="textarea" maxlength="255" v-model="addQuestionparam.optionB"></el-input>
                </el-form-item>
                <el-form-item label="选项C" prop="optionC">
                    <el-input autosize type="textarea" maxlength="255" v-model="addQuestionparam.optionC"></el-input>
                </el-form-item>
                <el-form-item label="选项D" prop="optionD">
                    <el-input autosize type="textarea" maxlength="255" v-model="addQuestionparam.optionD"></el-input>
                </el-form-item>
                <el-form-item label="答案选择" prop="answer">
                    <el-select v-model="addQuestionparam.answer" placeholder="请选择答案">
                        <el-option v-for="(item,index) in 'ABCD'" :key="index" :label="item" :value="item"></el-option>
                    </el-select>
                </el-form-item>


            </el-form>

            <span slot="footer" class="dialog-footer">
                <el-button @click="resetForm">重置</el-button>
                <el-button type="primary" @click="addQuestion">确 定</el-button>
            </span>
        </el-dialog>

        <!-- 第二部分 -->
        <el-table :data="tableData" style="width: 100%">
            <el-table-column type="index" label="序号" width="100"></el-table-column>
            <el-table-column label="章节" width="100">
                <template slot-scope="scoped">
                    <span>第{{scoped.row.chapter}}章</span>
                </template>
            </el-table-column>
            <el-table-column label="题目编号" prop="questionNumber" width="100"></el-table-column>
            <el-table-column label="题目描述" prop="description"></el-table-column>
            <!-- 折叠的选项区域 -->
            <el-table-column label="选项" type="expand">
                <template slot-scope="props" class="optionView">
                    <el-form label-position="left" inline class="demo-table-expand">
                        <el-form-item label="A:">
                            <span>{{ props.row.optionA }}</span>
                        </el-form-item>
                        <el-form-item label="B:">
                            <span>{{ props.row.optionB }}</span>
                        </el-form-item>
                        <el-form-item label="C:">
                            <span>{{ props.row.optionC }}</span>
                        </el-form-item>
                        <el-form-item label="D:">
                            <span>{{ props.row.optionD }}</span>
                        </el-form-item>
                    </el-form>
                </template>
            </el-table-column>
            <el-table-column label="答案" prop="answer" width="100">
            </el-table-column>
            <el-table-column label="操作" width="140">
                <template slot-scope="scoped">
                    <el-button type="primary" icon="el-icon-edit" circle @click="editChoose(scoped.row.id)"></el-button>
                    <el-button type="danger" icon="el-icon-delete" circle
                        @click="deleteChoose(scoped.row.id)"></el-button>
                </template>
            </el-table-column>
        </el-table>

        <!-- 修改选择题对话框 -->
        <el-dialog title="修改题目" :visible.sync="UpdateChooseQuestionFold" width="50%" :before-close="UpdatehandleClose">
            <!-- form 表单 -->
            <el-form :model="UpdateQuestionparam" :rules="rules" ref="UpdateruleForm" label-width="100px"
                class="demo-ruleForm">
                <!-- 题目编号 -->
                <el-form-item label="题目编号">
                    <el-input disabled v-model="UpdateQuestionparam.questionNumber">
                    </el-input>
                </el-form-item>
                <!-- 章节选择 -->
                <el-form-item label="章节选择" prop="chapterId">
                    <el-select v-model="UpdateQuestionparam.chapterId" placeholder="请选择章节">
                        <el-option v-for="(item,index) in chapters" :key="index"
                            :label="item.chapterNumber+item.description" :value="item.id"></el-option>
                    </el-select>
                </el-form-item>
                <!-- 题目描述 -->
                <el-form-item label="题目描述" prop="description">
                    <el-input autosize type="textarea" maxlength="255"
                        v-model="UpdateQuestionparam.description"></el-input>
                </el-form-item>
                <!-- ABCD四个选项 -->
                <el-form-item label="选项A" prop="optionA">
                    <el-input autosize type="textarea" maxlength="255" v-model="UpdateQuestionparam.optionA"></el-input>
                </el-form-item>
                <el-form-item label="选项B" prop="optionB">
                    <el-input autosize type="textarea" maxlength="255" v-model="UpdateQuestionparam.optionB"></el-input>
                </el-form-item>
                <el-form-item label="选项C" prop="optionC">
                    <el-input autosize type="textarea" maxlength="255" v-model="UpdateQuestionparam.optionC"></el-input>
                </el-form-item>
                <el-form-item label="选项D" prop="optionD">
                    <el-input autosize type="textarea" maxlength="255" v-model="UpdateQuestionparam.optionD"></el-input>
                </el-form-item>
                <el-form-item label="答案选择" prop="answer">
                    <el-select v-model="UpdateQuestionparam.answer" placeholder="请选择答案">
                        <el-option v-for="(item,index) in 'ABCD'" :key="index" :label="item" :value="item"></el-option>
                    </el-select>
                </el-form-item>
            </el-form>
            <span slot="footer" class="dialog-footer">
                <el-button @click="UpdateresetForm">重置</el-button>
                <el-button type="primary" @click="UpdateQuestion">确 定</el-button>
            </span>
        </el-dialog>

        <!-- 分页查询 -->
        <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange"
            :current-page="param.currentPage" :page-sizes="[5, 8, 10]" :page-size="param.pageSize"
            layout="total, sizes, prev, pager, next, jumper" :total="total">
        </el-pagination>

    </div>
</template>

<script>
    export default {
        watch: {
            'param.chapterId': { // 监视param对象中的 chapterId 章节id 属性变化  
                handler(newVal) {
                    // TODO 注意，这里的这个 questionNumber 清空之后还要再发一次请求。后面再处理
                    this.param.questionNumber = ""
                    // 因为  param.chapterId 发生变化 这里就会自动发送一次请求
                    this.getChooseQuestionlist()
                },
            },
            'param.questionNumber': { // 监视param对象中的 questionNumber 属性是否为空 
                handler(newVal) {
                    if (newVal === null || newVal === "") {
                        this.getChooseQuestionlist()
                    }
                },
            },
        },

        created() {
            this.getChapter()
            this.getChooseQuestionlist()
        },

        data() {
            // 判断编码是否重复
            var cf = (value) => {
                for (let i = 0; i < this.tableData.length; i++) {
                    if (value === this.tableData[i].questionNumber) {
                        return true
                    }
                }
                return false
            }
            // 编号表单验证
            var questionNumberRule = (rule, value, callback) => {
                var regex = /^C-[A-F0-9][0-9]{2,}$/;
                if (!value) {
                    return callback(new Error('请输入编号'));
                } else if (!regex.test(value)) {
                    return callback(new Error('编码格式不满足'));
                } else if (cf(value)) {
                    callback(new Error('编码已经存在'));
                } else {
                    callback();
                }
            };
            return {
                // 章节信息
                chapters: [],
                // 分页查询参数
                param: {
                    chapterId: 1,               // 章节id,select选择框的内容
                    questionNumber: "",         // 题目编号
                    currentPage: 1,              // 页数
                    pageSize: 5                  // 每页记录数
                },
                // 添加题目需要的数据
                addQuestionparam: {
                    questionNumber: "",          // 题目编号
                    chapterId: null,             // 章节id
                    description: "",             // 题目描述
                    optionA: "",                 // A选项
                    optionB: "",                 // B选项
                    optionC: "",                 // C选项
                    optionD: "",                 // D选项
                    answer: ""                   // 答案
                },
                // 修改题目需要的数据
                UpdateQuestionparam: {
                    id: null,                     // 题目id
                    questionNumber: "",          // 题目编号
                    chapterId: null,             // 章节id
                    description: "",             // 题目描述
                    optionA: "",                 // A选项
                    optionB: "",                 // B选项
                    optionC: "",                 // C选项
                    optionD: "",                 // D选项
                    answer: ""                   // 答案
                },


                // 表格数据
                tableData: [],
                // 总条数
                total: 0,
                // 控制对话框的开关
                addChooseQuestionFold: false,
                // 控制修改题目的对话框
                UpdateChooseQuestionFold: false,
                // 表单验证
                rules: {
                    questionNumber: [
                        { validator: questionNumberRule, trigger: 'blur' }
                    ],
                    description: [
                        { required: true, message: '请输入题目描述', trigger: 'blur' },
                    ],
                    optionA: [
                        { required: true, message: '选项A不能为空', trigger: 'blur' },
                    ],
                    optionB: [
                        { required: true, message: '选项B不能为空', trigger: 'blur' },
                    ],
                    optionC: [
                        { required: true, message: '选项C不能为空', trigger: 'blur' },
                    ],
                    optionD: [
                        { required: true, message: '选项D不能为空', trigger: 'blur' },
                    ],
                    answer: [
                        { required: true, message: '答案不能为空', trigger: 'blur' },
                    ],
                    chapterId: [
                        { required: true, message: '请选择章节', trigger: 'blur' },
                    ]
                }
            }
        },

        methods: {
            // 获取章节信息
            async getChapter() {
                const { data: res } = await this.$axios.get("/chapter/getChapter")
                this.chapters = res.data
            },
            // 分页查询，发送请求
            async getChooseQuestionlist() {
                const { data: res } = await this.$axios.post("/Choose/getChooseQuestion", this.param)
                this.tableData = res.data.records
                this.total = res.data.total
            },
            // 删除题目
            async deleteChoose(id) {
                const { data: res } = await this.$axios.delete("/Choose/deleteChoose", {
                    params: {
                        id: id,//题目id
                    }
                })
                if (res.code == 200) {
                    this.getChooseQuestionlist()
                    return this.$message.success("删除成功")
                }
                if (res.code == 512) {
                    return this.$message.error("此题目关联了试卷，不能删除")
                }
                return this.$message.error("网络错误")
            },

            // 分页查询
            getChooseQuestion() {
                this.getChooseQuestionlist()
            },
            handleSizeChange(newPageSize) {
                this.param.pageSize = newPageSize
                this.getChooseQuestion()
            },
            handleCurrentChange(newCurrent) {
                this.param.currentPage = newCurrent
                this.getChooseQuestion()
            },

            // 添加题目对话框关闭前的操作
            handleClose() {
                this.resetForm()
                this.addChooseQuestionFold = false
            },
            // 重置添加题目
            resetForm() {
                this.$refs.ruleForm.resetFields();
            },
            // 添加题目
            addQuestion() {
                this.$refs.ruleForm.validate(async valid => {
                    if (!valid) return this.$message.error("请完善表格")
                    const { data: res } = await this.$axios.post('/Choose/addQuestion', this.addQuestionparam)
                    if (res.code === 200) {
                        this.getChooseQuestionlist()
                        this.handleClose()
                        return this.$message.success("添加成功")
                    } else if (res.code === 511) {
                        return this.$message.error("编码重复")
                    } else if (res.code === 301) {
                        return this.$message.error("请完善信息")
                    } else {
                        return this.$message.error("你输入的信息有误")
                    }
                })
            },

            // 修改题目打开口， 需要当行数据的id
            editChoose(id) {
                this.UpdateQuestionparam.id = id
                this.UpdateChooseQuestionFold = true
                var data = this.tableData.find(item => item.id === id)
                this.UpdateQuestionparam.questionNumber = data.questionNumber
                this.UpdateQuestionparam.chapterId = data.chapter
                this.UpdateQuestionparam.description = data.description
                this.UpdateQuestionparam.optionA = data.optionA
                this.UpdateQuestionparam.optionB = data.optionB
                this.UpdateQuestionparam.optionC = data.optionC
                this.UpdateQuestionparam.optionD = data.optionD
                this.UpdateQuestionparam.answer = data.answer
            },
            // 修改题目对话框关闭前的操作
            UpdatehandleClose() {
                this.UpdateresetForm()
                this.UpdateChooseQuestionFold = false
            },
            // 重置修改题目的表单数据
            UpdateresetForm() {
                this.$refs.UpdateruleForm.resetFields();
            },
            // 发送请求，更改数据。
            UpdateQuestion() {
                this.$refs.UpdateruleForm.validate(async valid => {
                    if (!valid) return this.$message.error("请完善表格")
                    const { data: res } = await this.$axios.post('/Choose/updateQuestion', this.UpdateQuestionparam)
                    if (res.code === 200) {
                        this.getChooseQuestionlist()
                        this.UpdatehandleClose()
                        return this.$message.success("修改成功")
                    } else if (res.code === 512) {
                        return this.$message.error("不能修改答案，该试题已经关联试卷")
                    } else {
                        return this.$message.error("网络错误")
                    }
                })
            },
        }
    }
</script>

<style lang="less" scoped>
    /* 全局样式 */
    .main_container {
        height: 100%;
    }

    /* 头部样式 */
    .Header {
        margin-bottom: 15px;

        /* 选择框 */
        .el-select {
            width: 300px;
        }

        /* 添加题目按钮 */
        .addChooseButton {
            text-align: right;

            .el-button {
                margin-right: 50px;
            }
        }
    }

    /* 答案选项 */
    .el-form-item {
        margin-bottom: 0 !important;
    }

    /* 添加题目对话框 */
    .el-dialog {
        .Error_prompt {
            margin-left: 100px;
            color: red;
        }

        .el-form-item {
            margin-bottom: 20px !important;
        }
    }
</style>